<?php
declare (strict_types=1);

namespace app\api\controller;

use app\BaseController;
use think\db\exception\DbEventException;
use think\Request;

class Admin extends BaseController
{
    /**
     * @param Request $request
     * @return \think\response\Json
     */
    public function index(Request $request)
    {
        $keywords = $request->get('keyword');
        $data = \app\common\model\Admin::getAdmin($keywords);
        return success($data);
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //
    }

    /**
     * 保存新建的资源
     *
     * @param \think\Request $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $password = $request->post('password');
        $data = $request->post();
        if (empty($password)) {
            $data['password'] = md5(md5('123123'));
        }
        $data['password'] = md5(md5($data['password']));

        try {
            $res = \app\common\model\Admin::create($data);
        } catch (DbEventException $exception) {
            return fail($exception->getMessage());
        }
        return success($res);

    }

    /**
     * 显示指定的资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function read($id)
    {
        $data = \app\common\model\Admin::adminInfo($id);
        return success($data);
    }


    /**
     * 保存更新的资源
     *
     * @param \think\Request $request
     * @param int $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        $type = $request->put('type');
        $password = $request->put('password', '123456');
        $password = md5(md5($password));
        if ($type == 'reset_pwd') {
            \app\common\model\Admin::resetPassword($password, $id);
        } else {
            $data = $request->put();
            \app\common\model\Admin::updateAdmin($data, $id);
        }
        $list = \app\common\model\Admin::adminInfo($id);
        return success($list);
    }

    /**
     * 删除指定资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function delete($id)
    {
        if (empty($id) || $id == 0) {
            return fail('id值为空');
        }

        \app\common\model\Admin::delAdmin($id);
    }
}
